<template>
  <div class="p-4">
    <a-button @click="handleDBInit">插入1W条数据</a-button>
    <BasicTable @register="registerTable" />
  </div>
</template>
<script lang="ts">
  // 引入 sqlite3模块
  
  import moment from 'moment';
  const sqlite3 = require('sqlite3').verbose();

  import { defineComponent, ref } from 'vue';
  import { BasicTable, ColumnChangeParam, useTable } from '/@/components/Table';
  import { getBasicColumns, getBasicShortColumns, searchFormSchema } from './tableData';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { onMounted } from 'vue';
  export default defineComponent({
    components: { BasicTable },
    setup() {
      const loading = ref(false);
      const { createMessage } = useMessage();
      function onChange() {
        console.log('onChange', arguments);
      }
      const [
        registerTable,
        {
          setLoading,
          setColumns,
          getColumns,
          getDataSource,
          getRawDataSource,
          reload,
          getPaginationRef,
          setPagination,
          getSelectRows,
          getSelectRowKeys,
          setSelectedRowKeys,
          clearSelectedRowKeys,
        },
      ] = useTable({
        canResize: true,
        title: '加载列表示例',
        titleHelpMessage: '使用SQLite 查询大数据列表',
        api: handleDBQueryLst,
        columns: getBasicColumns(),
        rowKey: 'id',
        showTableSetting: false,
        onChange,
        rowSelection: {
          type: 'checkbox',
        },
        useSearchForm: true,
        formConfig: {
          labelWidth: 90,
          schemas: searchFormSchema,
        },
        onColumnsChange: (data: ColumnChangeParam[]) => {
          console.log('ColumnsChanged', data);
        },
      });

      const dbInst = ref<any | null>(null);

      const orderDbFile = ref('sqlite-db/order.db');

      const productNames = ref<string[]>([
        '智能手机',
        '平板电脑',
        '笔记本电脑',
        '蓝牙耳机',
        '智能手表',
        '沙发',
        '床',
        '床垫',
        '衣柜',
        '餐桌椅',
        'T恤',
        '衬衫',
        '牛仔裤',
        '运动鞋',
        '皮鞋',
        '牛奶',
        '巧克力',
        '饼干',
        '咖啡',
        '果汁',
        '洗面奶',
        '面膜',
        '粉底液',
        '口红',
        '香水',
        '小说',
        '传记',
        '漫画',
        '音乐专辑',
        '电影碟片',
        '跑步机',
        '哑铃',
        '健身车',
        '瑜伽垫',
        '运动手环',
        '狗粮',
        '猫砂',
        '宠物玩具',
        '宠物窝',
        '宠物衣服',
        '婴儿奶粉',
        '婴儿纸尿裤',
        '婴儿推车',
        '儿童玩具',
        '孕妇装',
        '充电器',
        '数据线',
        '移动电源',
        '鼠标',
        '键盘',
        '汽车坐垫',
        '汽车香水',
        '车载充电器',
        '行车记录仪',
        '汽车导航',
      ]);

      onMounted(async () => {
        dbInst.value = await new Promise((resolve) => {
          const db = new sqlite3.Database(orderDbFile.value, (err) => {
            if (err) {
              console.error(err.message);
            } else {
              console.log('Connected to the SQLite database.', db);
              resolve(db);
            }
          });
        });
        // console.log(
        //   '-----------------------onMounted ~ 完成数据库链接:-----------------------',
        //   dbInst.value,
        // );
      });

      function createId() {
        return `${Math.floor(Math.random() * 1000000) + 1000000}`;
      }

      function createCode() {
        return `${Math.floor(Math.random() * 100000000000000) + 100000000000000}`;
      }

      async function handleDBInit() {
        console.log('handleDBQueryLst ~ loading.value:', loading.value);
        if (loading.value) {
          console.log('正在loading, 请稍后操作');
          return;
        }
        console.log('handleDBQueryLst ~  dbInst.value:', dbInst.value);

        loading.value = true;
        console.log('handleDBInit ~ handleDBInit:', moment().format('YYYY-MM-DD HH:mm:ss'));
        // 创建数据库连接
        const db = new sqlite3.Database(orderDbFile.value, (err) => {
          if (err) {
            console.error(err.message);
          } else {
            console.log('Connected to the SQLite database.');
          }
        });

        try {
          // 插入数据
          console.log(
            '---------------------------开始插入数据---------------------------------',
            moment().format('YYYY-MM-DD HH:mm:ss'),
          );

          const list: any[] = [];

          for (let i = 0; i < 10 * 1000; i++) {
            const id = `${createId()}${i}`;
            const name = productNames.value[Math.floor(Math.random() * productNames.value.length)];
            list.push({
              id,
              name,
              bancode: createCode(),
            });
          }

          const query = 'INSERT INTO "product" ("id", "name", "bancode") VALUES ';
          const querySql = `${query} ${list
            .map((item) => `('${item.id}', '${item.name}', '${item.bancode}')`)
            .join(',')}`;

          console.log('handleDBInit ~ querySql:', querySql);
          db.run(querySql, (err) => {
            console.log('db.run ~ err', err);
          });

          console.log(
            '---------------------------完成插入数据---------------------------------',
            moment().format('YYYY-MM-DD HH:mm:ss'),
          );
        } catch (error) {
          console.log('handleDBInit ~ error:', error);
        } finally {
          loading.value = false;

          await new Promise((resolve) => {
            db.close((err) => {
              if (err) {
                console.error(err.message);
              }
              console.log('Close the database connection.');
              console.log(
                '---------------------------完成关闭数据库连---------------------------------',
                moment().format('YYYY-MM-DD HH:mm:ss'),
              );
              resolve(true);
            });
          });

          console.log('Close the database connection1');
        }

        reload();
      }

      async function handleDBQueryLst(pageParam) {
        const { page, pageSize, bancode, name, } = pageParam || {};
        if (loading.value) {
          return;
        }
        loading.value = true;
        // 创建数据库连接
        const db = new sqlite3.Database(orderDbFile.value, (err) => {
          if (err) {
            console.error(err.message);
          } else {
            console.log('Connected to the SQLite database.');
          }
        });

        let queryData = {};

        try {
          // 查询数据
          console.log(
            '---------------------------开始查询数据---------------------------------',
            moment().format('YYYY-MM-DD HH:mm:ss'),
          );
          queryData = await new Promise((resolve, reject) => {
            console.log('-------------begin--------------');
            // 查询数据总数
            let total = 0;

            const whereParams = [` 1 = 1`];
            if (name) {
              whereParams.push(`name like '%${name}%'`);
            }
            if (bancode) {
              whereParams.push(`bancode like '%${bancode}%'`);
            }
            const whereSql = `where ${whereParams.join(' and ')}`;
            db.get(`SELECT count(*) as total FROM product ${whereSql}`, (err, row) => {
              if (err) {
                console.log('查询数据总数失败：', err);
                reject(err);
                return;
              } else {
                console.log('查询数据总数成功：', row.total);
                total = row.total;
              }
            });

            // 查询数据
            db.all(
              `SELECT * FROM product  ${whereSql} LIMIT ${pageSize} OFFSET ${pageSize * (page - 1)}`,
              (err, rows) => {
                console.log('db.all ~ rows:', rows);
                if (err) {
                  console.log('查询数据 ~ err:', err);
                  reject(err);
                } else {
                  resolve({
                    total,
                    items: rows,
                  });
                }
              },
            );
          });
          console.log(
            '---------------------------完成查询数据---------------------------------',
            moment().format('YYYY-MM-DD HH:mm:ss'),
          );
          console.log('数据查询结果queryData:', queryData);
        } catch (error) {
          console.log('handleDBQueryLst ~ error:', error);
        } finally {
          loading.value = false;

          await new Promise((resolve) => {
            db.close((err) => {
              if (err) {
                console.error(err.message);
              }
              console.log('Close the database connection.');
              console.log(
                '---------------------------完成关闭数据库连---------------------------------',
                moment().format('YYYY-MM-DD HH:mm:ss'),
              );
              resolve(true);
            });
          });

          console.log('Close the database connection1');
        }

        return queryData;
      }

      function changeLoading() {
        setLoading(true);
        setTimeout(() => {
          setLoading(false);
        }, 1000);
      }
      function changeColumns() {
        setColumns(getBasicShortColumns());
      }
      function reloadTable() {
        setColumns(getBasicColumns());

        reload({
          page: 1,
        });
      }
      function getColumn() {
        createMessage.info('请在控制台查看！');
        console.log(getColumns());
      }

      function getTableData() {
        createMessage.info('请在控制台查看！');
        console.log(getDataSource());
      }

      function getTableRawData() {
        createMessage.info('请在控制台查看！');
        console.log(getRawDataSource());
      }

      function getPagination() {
        createMessage.info('请在控制台查看！');
        console.log(getPaginationRef());
      }

      function setPaginationInfo() {
        setPagination({
          current: 2,
        });
        reload();
      }
      function getSelectRowList() {
        createMessage.info('请在控制台查看！');
        console.log(getSelectRows());
      }
      function getSelectRowKeyList() {
        createMessage.info('请在控制台查看！');
        console.log(getSelectRowKeys());
      }
      function setSelectedRowKeyList() {
        setSelectedRowKeys(['0', '1', '2']);
      }
      function clearSelect() {
        clearSelectedRowKeys();
      }

      return {
        dbInst,
        loading,
        productNames,
        orderDbFile,
        registerTable,
        changeLoading,
        changeColumns,
        reloadTable,
        getColumn,
        getTableData,
        getTableRawData,
        getPagination,
        setPaginationInfo,
        getSelectRowList,
        getSelectRowKeyList,
        setSelectedRowKeyList,
        clearSelect,
        onChange,

        handleDBInit,
        handleDBQueryLst,
        createId,
        createCode,
      };
    },
  });
</script>
